# -*-coding:utf-8-*-
import re

from rest_framework import serializers

from areas.models import Area, Address


class AreasSerializer(serializers.ModelSerializer):
    """行政区划信息序列化器"""

    class Meta:
        model = Area
        fields = ("id", "name")


class AddressSerializers(serializers.ModelSerializer):
    """收货地址序列化器"""
    """显示指名地址的id"""
    province_id = serializers.IntegerField(label='省ID', required=True,write_only= True)
    city_id = serializers.IntegerField(label='市ID', required=True,write_only= True)
    district_id = serializers.IntegerField(label='区ID', required=True,write_only= True)

    """序列化输出"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)


    class Meta:
        model = Address
        exclude = ('user',)

    def validated_mobile(self, value):
        """
        验证手机号格式
        :param value:
        :return:
        """
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value


    def create(self, validated_data):
        """
        重写父类方法
        需要在验证后的数据添加user
        :param validated_data:
        :return:
        """
        user = self.context['request'].user
        validated_data['user'] = user
        address = super().create(validated_data)
        return address



